<?php

namespace Frieza\Modules\AdServing\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdServing\Assets;
use Doraemon\service\AdServing\AssetsService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AdAssetsController extends Controller
{
    const PAGE_SIZE = 50;

    /**
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function getList(Request $request, Content $content): Content
    {
        $params = $request->all();
        $params['page'] = $request->input('page', 1);
        $params['per_page'] = $request->input('per_page', self::PAGE_SIZE);
        if (isset($params['id'])) {
            $request->merge(['id' => $params['id']]);
        }
        return $content
            ->header('素材管理')
            ->breadcrumb(['text' => 'APP投放管理'])
            ->body(self::listAction($params));
    }

    /**
     * @param array $params
     * @return Grid
     */
    private function listAction(array $params = []): Grid
    {
        $listAndTotal = AssetsService::getFilterData($params);
        $gridModel = new pGridDataModel($listAndTotal['list'], $listAndTotal['total'], [
            'perPage' => $params['per_page'],
        ]);

        return Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('field', '属性字段名称')->placeholder('请输入属性字段名称');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('name', '属性值中文名称')->placeholder('请输入属性值中文名称');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('code', '属性值英文名称')->placeholder('请输入属性值英文名称');
                });
                $filter->expand();
            });

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->column('field', '属性字段名称');
            $grid->column('code', '属性值英文名称');
            $grid->column('name', '属性值中文名称');
            $grid->column('addtime', '创建时间')->display(function () {
                return $this->addtime ? date('Y-m-d H:i:s', $this->addtime) : 0;
            });
            $grid->column('edittime', '更新时间')->display(function () {
                return $this->edittime ? date('Y-m-d H:i:s', $this->edittime) : 0;
            });
        });
    }

    /**
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, int $id = 0): Content
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑素材';
        } else {
            $title = '创建素材';
        }

        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('素材管理')
            ->breadcrumb(
                [
                    'text' => '素材列表',
                    'url' => '/adServing/assets'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    /**
     * @param $id
     * @return JsonResponse
     */
    public function del($id): JsonResponse
    {
        $rs = AssetsService::delAssets($id);
        if ($rs === true) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败," . $rs,
            ]);
        }
    }

    /**
     * @param int $id
     * @return Form
     */
    private function editAction(int $id = 0): Form
    {
        if ($id > 0) {
            $data = Assets::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->text('field', '属性字段名称')->required('属性字段名称必填')->help('64个字符以下');
        $form->text('code', '素材英文名')->required('英文名必填')->help('64个字符以下');
        $form->text('name', '素材中文名')->required('中文名必填')->help('64个字符以下');
        $form->text('info', '描述')->placeholder('请输入该数据域的详细信息');

        $form->action('/admin/adServing/assets/save');

        return $form;
    }


    public function save(Request $request)
    {
        $params = $request->all();
        $rs = AssetsService::addAssets($params);
        if ($rs === true) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/adServing/assets')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败,' . $rs,
            ]);
            return back()->with(compact('error'));
        }
    }
}
